﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Diagnostics;
using DanielVaughan.Logging;

namespace OutputTree
{
    public partial class OutputTreeControl : UserControl
    {
        private OutputItem lastItem;
        private Stack<OutputItem> indentStack;
        private ScrollViewer scrollHost;
        private ILog log;

        public ILog Log
        {
            set 
            { 
                log = value; 
            }
        }

        public OutputTreeControl()
        {
            indentStack = new Stack<OutputItem>();

            InitializeComponent();
        }

        public void Return()
        {
            if (indentStack.Count > 0)
            {
                indentStack.Clear();
            }
        }

        public void Unindent()
        {
            if (indentStack.Count > 0)
            {
                indentStack.Pop();
            }
        }

        public void Indent()
        {
            indentStack.Push(lastItem);
        }

        public TreeViewItem ParentItem
        {
            get
            {
                if (indentStack.Count > 0)
                {
                    var outputItem = indentStack.Peek();

                    return outputItem.TreeViewItem;
                }
                else
                {
                    return null;
                }
            }
        }

        public void WriteLine(string message)
        {
            WriteLine(Colors.Black, message);
        }

        public void WriteLine(string format, params object[] args)
        {
            WriteLine(Colors.Black, format, args);
        }

        public void WriteLine(Color color, string message, bool skipLog = false)
        {
            var outputItem = new OutputItem(message, color);

            log.Info(message);

            outputItem.NodeContentCreated += (sender, e) =>
            {
                scrollHost = OutputTreeView.GetScrollHost();

                scrollHost.ScrollIntoView(e.OutputItem.TreeViewItem);
            };

            if (this.ParentItem == null)
            {
                OutputTreeView.Items.Add(outputItem);
            }
            else
            {
                this.ParentItem.Items.Add(outputItem);
            }

            lastItem = outputItem;
        }

        public void WriteLine(Color color, string format, params object[] args)
        {
            var message = string.Format(format, args);

            WriteLine(color, message);
        }
    }
}
